package com.yaorange.exception.handler;

import com.yaorange.exception.BusinessException;
import com.yaorange.response.Result;
import com.yaorange.response.enums.ResultCode;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBusinessException(BusinessException e) {
        e.printStackTrace();
        return Result.fail(e.getCode(),e.getMessage());
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return Result.fail(ResultCode.VALIDATE_FAILED.getCode(), errors.toString());
    }

    @ExceptionHandler(Exception.class)
    public Result<?> handleOtherException(Exception e) {
        e.printStackTrace();
        // 打印日志：e.printStackTrace();
        return Result.fail("服务器内部错误：" + e.getMessage());
    }
}